package com.qian2.pricesharingapplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.lb2.JSONParser;
import com.example.pricesharingapplication.R;
import com.google.zxing.client.android.CaptureActivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class NewProductActivity extends Activity {

	static final int REQUEST_IMAGE_CAPTURE = 1;
	static final int REQUEST_IMAGE_SELECT = 2;
	static final int REQUEST_BARCODE = 3;
	String imageFilePath = null;
	String uid = null;

	//TODO onActivityResult
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println("NewProductActivity.onActivityResult() resultCode : "+ resultCode);
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_IMAGE_CAPTURE) {

				imageFilePath = Environment.getExternalStorageDirectory().
			    	    getAbsolutePath() + "/picture.jpg";;
				
				Log.d("NewProductActivity", "imageFilePath : " + imageFilePath);
				try {
				
					TextView inputImagePath = (TextView) findViewById(R.id.inputImagePath);
					inputImagePath.setText(scaleDown(imageFilePath, 1000, true));
					ImageView uploadPhotoView = (ImageView) findViewById(R.id.uploadPhotoView);
					Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath);
					boolean filter = false;
					DisplayMetrics displaymetrics = new DisplayMetrics();
					getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
					int screen_width = displaymetrics.widthPixels;
					int pic_witdth=bitmap.getWidth();
					int pic_height=bitmap.getHeight();
					int target_width= Integer.parseInt(Long.toString(Math.round(screen_width*0.25))); 
					int target_height=Integer.parseInt(Long.toString(Math.round(screen_width*0.25/pic_witdth*pic_height)));
					
					bitmap=Bitmap.createScaledBitmap(bitmap, target_width,target_height, filter);													// bitmap
					//ImageView image_view = (ImageView) findViewById(R.id.imageView1);
					uploadPhotoView.setImageBitmap(bitmap);
					int target_scale=Integer.parseInt(Long.toString(Math.round(screen_width*0.25)));
					uploadPhotoView.setMinimumHeight(target_scale);
					uploadPhotoView.setMinimumWidth(target_scale);
					//uploadPhotoView.setImageBitmap(Bitmap.createScaledBitmap(bMap, bMap.getWidth(), bMap.getHeight(), false));
					//uploadPhotoView.setMaxHeight(100);
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//cursor.close();
			} else 	if (requestCode == REQUEST_BARCODE) {		
				// Handle successful scan		
				String contents = data.getStringExtra("SCAN_RESULT");		
				EditText barcode_result=(EditText) findViewById(R.id.inputUPC);		
				barcode_result.setText(contents);		
				data.getStringExtra("SCAN_RESULT_FORMAT");		
				data.getByteArrayExtra("SCAN_RESULT_BYTES");		
				int intentOrientation = data.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);		
				data.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
				}
			else if (requestCode == REQUEST_IMAGE_SELECT) {
				Uri _uri = data.getData();

				// User had pick an image.
				Cursor cursor = getContentResolver()	
						.query(_uri,new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },	null, null, null);
				cursor.moveToFirst();
				// Link to the image
				imageFilePath = cursor.getString(0);

				TextView inputImagePath = (TextView) findViewById(R.id.inputImagePath);
				inputImagePath.setText(scaleDown(imageFilePath, 1000, true));
				ImageView uploadPhotoView = (ImageView) findViewById(R.id.uploadPhotoView);
				Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath);
				boolean filter = false;
				DisplayMetrics displaymetrics = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
				int screen_width = displaymetrics.widthPixels;
				int pic_witdth=bitmap.getWidth();
				int pic_height=bitmap.getHeight();
				int target_width= Integer.parseInt(Long.toString(Math.round(screen_width*0.25))); 
				int target_height=Integer.parseInt(Long.toString(Math.round(screen_width*0.25/pic_witdth*pic_height)));
				
				bitmap=Bitmap.createScaledBitmap(bitmap, target_width,target_height, filter);													// bitmap
				//ImageView image_view = (ImageView) findViewById(R.id.imageView1);
				uploadPhotoView.setImageBitmap(bitmap);
				int target_scale=Integer.parseInt(Long.toString(Math.round(screen_width*0.25)));
				uploadPhotoView.setMinimumHeight(target_scale);
				uploadPhotoView.setMinimumWidth(target_scale);
				
				//scaleDown(imageFilePath, 1000, true);
				Toast.makeText(this, scaleDown(imageFilePath, 1000, true),
						Toast.LENGTH_SHORT).show();
				cursor.close();
			}
			super.onActivityResult(requestCode, resultCode, data);
		} else if (resultCode == RESULT_CANCELED) {
			Toast.makeText(this, "Picture was not taken or selected",
					Toast.LENGTH_SHORT).show();
		}
	}

	// Progress Dialog
	private ProgressDialog pDialog;

	JSONParser jsonParser = new JSONParser();
	EditText inputUPC;
	EditText inputName;
	EditText inputDesc;
	EditText inputBrand;
	Spinner inputCategory;

	// url to create new product
	private static String url_create_product = "http://wwwfyp.cse.ust.hk:7117/create_product.php";

	// JSON Node names
	//	private static final String TAG_SUCCESS = "success";
	//	private static final String TAG_MESSAGE = "message";
	//	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_product);

		// Edit Text
		inputUPC = (EditText) findViewById(R.id.inputUPC);
		inputName = (EditText) findViewById(R.id.inputName);
		inputCategory = (Spinner) findViewById(R.id.inputCategoryIDSpinner);
		inputDesc = (EditText) findViewById(R.id.inputDesc);
		inputBrand = (EditText) findViewById(R.id.inputBrand);
		
		inputName.setHint(R.string.mustInput);
		
		inputCategory.setOnItemSelectedListener(new CustomOnItemSelectedListener());	
		ImageButton barcode_button= (ImageButton) this.findViewById(R.id.UPC_scanner);
		barcode_button.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewProductActivity.this, CaptureActivity.class);
				intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
				startActivityForResult(intent, REQUEST_BARCODE );
				// See more at: http://techiedreams.com/android-zxing-barcode-scanner-integration/#sthash.YO6zAgBL.dpuf	
			}

		});
		// Create button
		Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
		Button upload_photo = (Button) findViewById(R.id.uploadPhotobtn);
		Button take_photo = (Button) findViewById(R.id.takePhotobtn);



		// button click event
		btnCreateProduct.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// creating new product in background thread
				String errorMessage = getString(R.string.mustInput);
				
				if (inputName.getText().length() == 0){
					inputName.setError(errorMessage);
					return;
				}
				new CreateNewProduct().execute();

			}
		});

		// button click event
		upload_photo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Log.v("NewProductActivity :", "Clicked Upload Button");
				// creating new product in background thread
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_PICK);
				int PICK_IMAGE = 2;
				Log.v("NewProductActivity :", "Choose Picture");

				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						PICK_IMAGE);

			}
		});

		take_photo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Log.v("NewProductActivity :", "Clicked Take Photo Button");
				// creating new product in background thread
			    String imageFilePath = Environment.getExternalStorageDirectory().
			    	    getAbsolutePath() + "/picture.jpg";  
			    	    File imageFile = new File(imageFilePath); 
			    	    Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri

			    	    Intent it = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
			    	    it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri); 
			    	    startActivityForResult(it, 1);

			}
		});
	}




	/**
	 * Background Async Task to Create new product
	 * 
	 * @throws Throwable
	 * */

	public static String scaleDown(String filepath, float maxImageSize,boolean filter) {
		Bitmap realImage = BitmapFactory.decodeFile(filepath);
		float ratio = Math.min(
				(float) maxImageSize / realImage.getWidth(),
				(float) maxImageSize / realImage.getHeight());
		int width = Math.round((float) ratio * realImage.getWidth());
		int height = Math.round((float) ratio * realImage.getHeight());

		Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
				height, filter);

		String root = Environment.getExternalStorageDirectory().toString();
		File myDir = new File(root + "/req_images");
		myDir.mkdirs();
		Random generator = new Random();
		int n = 10000;
		n = generator.nextInt(n);
		String[] new_filepath=filepath.split("\\.");
		System.out.println("xxx"+filepath);
		String new_filepath2 = "";
		System.out.println("xxx"+new_filepath.length);
		for (int i=0;i<new_filepath.length-1;i++){

			if (i!=new_filepath.length-2)
				new_filepath2 += new_filepath[i]+".";
			else 
				new_filepath2 += new_filepath[i];
		}
		System.out.println("xxx"+new_filepath2);
		new_filepath2=new_filepath2+"_temp.jpg";
		File file = new File(new_filepath2);
		//Log.i(TAG, "" + file);
		if (file.exists())
			file.delete();
		try {
			//			file.createNewFile();
			OutputStream out = new FileOutputStream(file);///*****************************************
			newBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new_filepath2;
	}

	public void upload(String filepath, String uid) throws IOException {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
		.permitAll().build();

		StrictMode.setThreadPolicy(policy);

		MultipartEntity entity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE);
		File fileToUpload = new File(filepath);
		FileBody fileBody = new FileBody(fileToUpload,
				"application/octet-stream");
		entity.addPart("file", fileBody);
		entity.addPart("uid", new StringBody(uid));

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(
				"http://wwwfyp.cse.ust.hk:7117/Picture/upload_file.php");
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost);

		response.getStatusLine().getStatusCode();
		EntityUtils.toString(response.getEntity());

		System.out.println("response from server :" + response);

	}

	class CreateNewProduct extends AsyncTask<String, String, JSONObject> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(NewProductActivity.this);
			pDialog.setMessage("Creating Product..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		protected JSONObject doInBackground(String... args) {
			String upc = inputUPC.getText().toString();
			String name = inputName.getText().toString();
			int category = inputCategory.getSelectedItemPosition();
			String description = inputDesc.getText().toString();
			String brand = inputBrand.getText().toString();

			System.out.println("upc:" + upc);
			System.out.println("name:" + name);
			System.out.println("category:" + category);
			System.out.println("description:" + description);
			System.out.println("brand:" + brand);
			
			if(category>=0 && category<=9){
				category++;
			}
			else if(category==10){
				category=0;
			}

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			params.add(new BasicNameValuePair("upc", upc));
			params.add(new BasicNameValuePair("name", name));
			params.add(new BasicNameValuePair("categoryID", Integer.toString(category)));
			params.add(new BasicNameValuePair("description", description));
			params.add(new BasicNameValuePair("brand", brand));

			for (int i = 0; i < params.size(); i++) {
				System.out.println("Create Response for params" + params.get(i).toString());

			}

			// getting JSON Object
			// Note that create product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(url_create_product,
					"POST", params);

			// check log cat fro response
			System.out.println("NewProductActivity: Response from server"
					+ json.toString());

			// check for success tag
			try {
				int success = json.getInt(StaticFinal.TAG_SUCCESS);

				if (success == 1) {
					// successfully created product

					String uid = json.getString("uid");
					if(imageFilePath != null )
						//					upload(imageFilePath, uid);
						// if(imageFilePath.toString() != null )					
						upload(scaleDown(imageFilePath, 1000, true), uid);
					// upload(imageFilePath);
					Intent i = new Intent(getApplicationContext(),
							ProductPage.class);
					i.putExtra("uid", uid);
					startActivity(i);

					// closing this screen
					//finish();
				} else {
					// failed to create product

				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return json;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(JSONObject json) {
			// dismiss the dialog once done
			pDialog.dismiss();
			try {
				Toast.makeText(NewProductActivity.this,
						json.getString(StaticFinal.TAG_MESSAGE).toString(),
						Toast.LENGTH_LONG).show();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
}
